from rest_framework import serializers
from django.contrib.auth import authenticate
from rest_framework_jwt.utils import jwt_payload_handler, jwt_encode_handler

class LoginSerializer(serializers.Serializer):
    username = serializers.CharField(write_only=True, max_length=100)
    password = serializers.CharField(write_only=True)

    def validate(self, attrs):
        username = attrs['username']
        password = attrs['password']

        user = authenticate(username=username, password=password)
        if not user:
            raise serializers.ValidationError('传统身份验证失败')

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return {
            'user': user,
            'token': token
        }

